package com.ruixin.server;

import com.ruixin.base.BaseTryCatch;
import com.ruixin.base.exception.BaseException;
import com.ruixin.base.factory.Factory;
import com.ruixin.mvc.config.ApplicationContextWrapper;
import com.ruixin.mvc.config.EnvironmentWrapper;
import com.ruixin.mvc.config.WebRegister;
import com.ruixin.servlet.DispatcherServlet;
import org.apache.catalina.Context;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.servlets.DefaultServlet;
import org.apache.catalina.startup.Tomcat;

import java.io.File;
import java.net.URL;

/**
 * tomcat容器
 */
public class TomcatServer {

    /**
     * 容器启动
     * @param contextWrapper
     * @throws BaseException
     */
    public void start(ApplicationContextWrapper contextWrapper) throws BaseException {
        BaseTryCatch.process(()->{
            Tomcat tomcat = new Tomcat();
            URL resource = TomcatServer.class.getResource("/");
            String path = resource.getPath();
            tomcat.setBaseDir(path);
            EnvironmentWrapper environment = contextWrapper.getEnvironment();
            int port = environment.getPort();
            String host = environment.getHost();
            tomcat.setPort(port);
            tomcat.setHostname(host);
            Connector connector = new Connector();
            tomcat.setConnector(connector);
            connector.setPort(port);
            Context context = tomcat.addContext(contextWrapper.getContextPath(), path);
            context.setName(environment.getServerName());
            tomcat.addServlet(context,"default",new DefaultServlet());
            tomcat.addServlet(context,"dispatcherServlet",new DispatcherServlet(contextWrapper));
            addStaticResourceMapping(context, contextWrapper.getWebRegister());
            context.addServletMappingDecoded("/","dispatcherServlet");
            tomcat.start();
        });
    }

    /**
     * 设置静态资源
     * @param context
     * @param webRegister
     */
    private void addStaticResourceMapping(Context context,WebRegister webRegister){
        Factory<String, String> staticFactory = webRegister.getStaticFactory();
        staticFactory.forEach((url,path)->{
            context.addServletMappingDecoded(url,"default");
        });
    }
}
